import time

from appium import webdriver as appdriver
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from Confing import *


class DriverTools:
    _driver_path = None
    _driver_web = None
    _driver_app = None
    _current_driver_type = None

    # 获取驱动路径
    @classmethod
    def get_driver_path(cls):
        if cls._driver_path is None:
            if ENV == "production":
                driver_path = os.path.abspath(
                    os.path.join(os.path.dirname(__file__), "..", "drivers", "chromedriver.exe"))
                return driver_path
            else:
                from webdriver_manager.chrome import ChromeDriverManager
                return ChromeDriverManager().install()
        return cls._driver_path


    # 创建web驱动
    @classmethod
    def web_driver(cls):
        if cls._driver_web is not None:
            return cls._driver_web
        else:
            options = Options()
            options.add_argument("--start-maximized")
            driver = webdriver.Chrome(
                service=Service(cls.get_driver_path()),
                options=options
            )
            cls._driver_web = driver
            return driver

    #web驱动退出
    @classmethod
    def quit_web(cls, driver):
        if cls._driver_web:
            driver.quit()
            cls._driver_web = None

    # 创建app驱动
    @classmethod
    def app_driver(cls):
        # 连接 Appium 服务器
        driver = appdriver.Remote(
            command_executor='http://localhost:4723',  # Appium 服务地址
            options=options
        )
        return driver

    # app驱动退出
    @classmethod
    def quit_app(cls, driver):
        # 关闭应用程序（而不是关闭driver会话）
        try:
            driver.terminate_app("com.android.settings")
            print("已关闭设置应用")
        except Exception as e:
            print(f"关闭应用时出错：{e}")
        if cls._driver_app:
            driver.quit()
            cls._driver_app = None

    # 创建web/app驱动
    @classmethod
    def get_driver(cls):
        if not hasattr(cls,"_driver_initialized"):
            driver_type = DRIVER_TYPE.lower()
            cls._current_driver_type = driver_type # 标记一下创建driver的类型
            if driver_type == "web":
                driver = cls.web_driver()
            elif driver_type == "app":
                driver = cls.app_driver()
            else:
                raise ValueError(f"不支持的 driver type: {driver_type}")
            cls._driver_initialized = True
            return driver
        else:
            if cls._current_driver_type == "web":
                return cls.web_driver()
            else:
                return cls.app_driver()

    # 退出web/app驱动
    @classmethod
    def quit_driver(cls):
        if cls._current_driver_type == "web":
            cls.quit_web(cls.web_driver())
        else:
            cls.quit_app(cls.app_driver())


if __name__ == '__main__':
    driver = DriverTools.get_driver()
    driver.get("https://www.baidu.com")
    time.sleep(2)